import React, { forwardRef, useImperativeHandle, useRef, useState } from 'react';
import { Button, message } from 'antd';
import { ModalForm, ProFormText, ProFormTextArea, ProFormSelect } from '@ant-design/pro-form';
import { update, getInfo, test } from '../service';


const UpdateForm = (props, ref) => {

  /** 编辑窗口的弹窗 */
  const [updateModalVisible, handleUpdateModalVisible] = useState(false);
  /** 绑定form表单 */
  const formRef = useRef();
    /** 传递参数默认值 */
    const defaultParam = '{"headers":{},"values":{}}'

    /**
   * 获得详情
   *
   * @param currentRow
   */

     const handleGetinfo = async (currentRow) => {
      formRef.current.resetFields();
      const hide = message.loading('加载详情');
      try {
       const result = await getInfo(currentRow.id);
        hide();
        message.success('加载成功');
        if(result.data.params){
          result.data.params = JSON.parse(result.data.params);
        }
        formRef.current.setFieldsValue(result.data);
      } catch (error) {
        hide();
        message.error('加载详情失败');
      }
    };

  /**
   * 测试数据源
   */
   const handleTest = async () => {
    const hide = message.loading('正在测试');
    try {
      const formValue = formRef.current.getFieldsValue();
      if(formValue.params){
        formValue.params = JSON.parse(formValue.params);
      }
      const value = await test(formValue);
      if(value.success){
        hide();
        message.success("测试成功");
      }else{
        message.error(value.errorMessage);
      }
      return true;
    } catch (error) {
      hide();
      message.error('测试失败');
      return false;
    }
  };

  /**
   * 更新节点
   *
   * @param fields
   */

   const handleUpdate = async (value) => {
    const hide = message.loading('正在更新');

    try {
      value.id=props.currentRow.id;
      await update(value);
      hide();
      message.success('更新成功');
      return true;
    } catch (error) {
      hide();
      message.error('更新失败请重试！');
      return false;
    }
  };

  /** 
   * 将子类组件的方法暴露给父组件
   * react规定必须使用useImperativeHandle方法，来保存并抛出想要传递给父组件的方法或者数据，
   * 第一个参数是ref,第二个参数是函数，返回想要抛出的对象集合
   * 
  */
  useImperativeHandle(ref, () => ({
    handleUpdateModalVisible,
    handleGetinfo,
  }));

  return (
    <ModalForm
      formRef={formRef}
      title="编辑数据源"
      width="50%"
      submitter={{
        render: (props, defaultDoms) => {
          return [
            ...defaultDoms,
            <Button
              key="test"
              onClick={() => {
                handleTest();
              }}
            >
              测试
            </Button>,
          ];
        },
      }}
      visible={updateModalVisible}
      onFinish={async (value) => {
        const success = await handleUpdate(value);

        if (success) {
          handleUpdateModalVisible(false);

          if (props.actionRef.current) {
            props.actionRef.current.reload();
          }
        }
      }}
      onVisibleChange={handleUpdateModalVisible}
    >
      <ProFormText
        width="90%"
        label="数据源名称"
        name="sourceName"
        rules={[
          {
            required: true,
            message: '请输入数据源名称',
          },
        ]}
        placeholder="数据源的名称"
      />
      <ProFormSelect
        label="数据源类型"
        name="sourceType"
        rules={[
          {
            required: true,
            message: '请选择数据源类型',
          },
        ]}
        options={[
          {
            label: 'MYSQL',
            value: 'MYSQL',
          },
          {
            label: 'HTTP',
            value: 'HTTP',
          },
        ]}
      />
      <ProFormTextArea
        width="90%"
        label="连接地址"
        name="url"
        rules={[
          {
            required: true,
            message: '请输入连接地址',
          },
        ]}
        placeholder="连接地址"
      />
      <ProFormText
        width="90%"
        label="用户名(数据库必填)"
        name="username"
        placeholder="数据库用户名"
      />
      <ProFormText

        width="90%"
        label="密码(数据库必填)"
        name="password"
        placeholder="数据库密码"
      />
      <ProFormTextArea
        width="90%"
        label="请求参数(HTTP接口,不填保持默认)"
        name="params"
        placeholder="请求参数"
        initialValue={defaultParam}
      />
      <ProFormSelect
        label="状态"
        name="state"
        rules={[
          {
            required: true,
            message: '请选择数据源类型',
          },
        ]}
        options={[
          {
            label: '启用',
            value: '1',
          },
          {
            label: '关闭',
            value: '0',
          },
        ]}
      />
      <ProFormTextArea
        width="90%"
        label="备注"
        name="remark"
        placeholder="备注信息"
      />
    </ModalForm>
  );
};

export default forwardRef(UpdateForm);
